import { useEffect, useState } from 'react';
import style from './index.module.scss';
import { Popover } from 'react-vant';
import classNames from 'classnames';
import { BaseUrl } from '@/utils/index';
import { showToast } from './util';

import gift1 from '@/assets/images/christmas/gift/gift1.png';
import gift2 from '@/assets/images/christmas/gift/gift2.png';
import gift3 from '@/assets/images/christmas/gift/gift3.png';
import gift4 from '@/assets/images/christmas/gift/gift4.png';
import pick from '@/assets/images/christmas/gift/pick.png';
import picked from '@/assets/images/christmas/gift/picked.png';

const giftList = [gift1, gift2, gift3, gift4];

const Gift = () => {
    const urlParams = new URLSearchParams(window.location.search);
    const authorizationToken = urlParams.get('userId');

    const [info, setInfo] = useState({
        totalGrowthValue: 0,
        userGrowthValue: 0,
        decorations: [],
    }); // 当前信息
    const [progress, setProgress] = useState(0);
    const [data, setData] = useState([
        {
            id: '1',
            name: '',
            url: gift1,
            status: 1, // 1不可领取、2 已领取、 3 待领取
        },
        {
            id: '2',
            name: '',
            url: gift2,
            status: 1, // 1不可领取、2 已领取、 3 待领取
        },
        {
            id: '3',
            name: '',
            url: gift3,
            status: 1, // 1不可领取、2 已领取、 3 待领取
        },
        {
            id: '4',
            name: '',
            url: gift4,
            status: 1, // 1不可领取、2 已领取、 3 待领取
        },
    ]);

    const handleResult = (result) => {
        setInfo({
            ...result,
        });
        setProgress(Math.floor((result.userGrowthValue / 4000) * 100));
        const list = (result?.decorations).map((item, i) => {
            return {
                ...item,
                url: giftList[i],
            };
        });

        setData(list);
    };

    const getGiftInfo = async () => {
        fetch(BaseUrl + `/gift/rank/christmas/user/growth/value`, {
            method: 'GET',
            headers: {
                Authorization: authorizationToken,
            },
        })
            .then((response) => response.json())
            .then((response) => {
                if (response.code === 200 && response.data) {
                    handleResult(response.data);
                    console.log('成功');
                } else {
                    console.error('Failed to fetch data:', response.msg);
                    showToast(response.msg);
                }
            })
            .catch((error) => console.error('Error fetching data:', error));
    };

    // 领取
    const clickPick = async (item) => {
        if (item.status <= 2) {
            return;
        }
        fetch(
            BaseUrl +
                `/gift/rank/christmas/decoration/receive?decorationId=${item.id}`,
            {
                method: 'POST',
                headers: {
                    Authorization: authorizationToken,
                    // 'content-type': 'application/json',
                },
                // body: JSON.stringify({
                //     decorationId: item.id,
                // }),
            }
        )
            .then((response) => response.json())
            .then((response) => {
                if (response.code === 200) {
                    getGiftInfo();
                    console.log('成功');
                } else {
                    console.error('Failed to fetch data:', response.msg);
                    showToast(response.msg);
                }
            })
            .catch((error) => console.error('Error fetching data:', error));
    };

    useEffect(() => {
        if (authorizationToken) {
            getGiftInfo();
        } else {
            console.error('Authorization token not found in URL');
        }
    }, []);

    return (
        <div className={style.gift_container}>
            <div className={style.gift_box}>
                <div className={style.top_box}>
                    <Popover
                        theme="dark"
                        placement={'bottom-start'}
                        reference={<div className={style.message}></div>}
                    >
                        <div className={style.popover_content}>
                            用户可以通过完成特定任务使圣诞树成长(如领取圣诞帽、
                            发布动态带上圣诞话题，赠送圣诞专属礼物)成长后获得
                            虚拟装饰品。领取圣诞帽+10点成长值，带上圣诞话题
                            +300成长值。
                        </div>
                    </Popover>
                    <div className={style.gift_wrap}>
                        <div className={style.progress_text}>
                            {info?.userGrowthValue || 0}/4000
                        </div>
                        <div className={style.progress}>
                            <div
                                className={style.progress_bar}
                                style={{ width: `${progress}%` }}
                            ></div>
                        </div>
                    </div>
                </div>
                <div className={style.bottom_box}>
                    {data.map((item) => (
                        <div className={style.item} key={item.id}>
                            <div className={style.gift}></div>
                            <div
                                className={classNames(style.content, {
                                    [style.content_gray]: item?.status === 1,
                                })}
                            >
                                <img src={item.url} alt="" />
                                <div
                                    className={style.pickBtn}
                                    onClick={() => clickPick(item)}
                                >
                                    <img
                                        src={item?.status === 2 ? picked : pick}
                                        alt=""
                                    />
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
};

export default Gift;
